<template>
<div>
  <div class="crumbs">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        <i class="el-icon-pie-chart"></i> 数据统计分析列表
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="container">
    <el-table
        :data="tableData" border class="table" ref="multipleTable"
        header-cell-class-name="table-header"
    >
      <el-table-column prop="configName" label="配置名"></el-table-column>
      <el-table-column prop="fileName" label="文件名"></el-table-column>
      <el-table-column label="查看历史分析">
        <template #default="scope">
          <el-button type="text" class="yellow" @click="handleAnalysisResult(scope.row.id)">查看分析结果</el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="text" @click="startAnalysis(scope.$index)">分析</el-button>
          <el-button type="text" @click="handlePipeline(scope.row.id)">新建流水线</el-button>
          <br/>
          <el-button type="text" class="red" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <div class="pagination">
      <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                     :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
    </div>

    <el-dialog title="新建可视化分析" v-model="analysisVisible" width="50%">
      <el-form label-width="150px" label-position="left">
        <el-form-item label="分析方法：" required>
          <el-select v-model="analysisType" placeholder="请选择" class="handle-select mr10" @change="changeMethodMsg">
            <el-option key="1" label="数据分布" value="DATA_DISTRIBUTION"></el-option>
            <el-option key="2" label="散点图" value="SCATTER_PLOT"></el-option>
            <el-option key="3" label="数据统计" value="STATISTICS"></el-option>
            <el-option key="4" label="偏度-峰度" value="SKEWNESS_KURTOSIS"></el-option>
            <el-option key="5" label="皮尔森相关系数" value="PEARSON"></el-option>
          </el-select>
        </el-form-item>
        <el-alert type="info" show-icon style="margin-bottom: 20px">{{methodMsg}}</el-alert>
        <el-form-item label="配置拥有字段数：" >
          {{selectConfigLen}}
        </el-form-item>
        <el-form-item label="配置拥有字段：">
          <el-table :data="selectConfigCol" border class="table"  header-cell-class-name="table-header" size="small">
            <el-table-column label="字段名">
              <template #default="scope"><span>{{scope.row}}</span></template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="analysisVisible = false" size="medium">再想想</el-button>
                    <el-button type="primary" @click="analysis" size="medium">确定</el-button>
                </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="pipelineVisible"
        title="新建流水线"
        :before-close="handleClose"
    >
      <el-form label-position="left" label-width="120px">
        <el-form-item label="流水线名称：" required>
          <el-input v-model="pplForm.pipelineName"></el-input>
        </el-form-item>
        <el-form-item label="分析方法：" required>
          <el-select v-model="pplForm.func" placeholder="请选择" class="handle-select mr10" @change="changeMethodMsg2">
            <el-option key="1" label="数据分布" value="DATA_DISTRIBUTION"></el-option>
            <el-option key="2" label="散点图" value="SCATTER_PLOT"></el-option>
            <el-option key="3" label="数据统计" value="STATISTICS"></el-option>
            <el-option key="4" label="偏度-峰度" value="SKEWNESS_KURTOSIS"></el-option>
            <el-option key="5" label="皮尔森相关系数" value="PEARSON"></el-option>
          </el-select>
        </el-form-item>
        <el-alert type="info" show-icon style="margin-bottom: 20px">{{methodMsg2}}</el-alert>
        <el-form-item label="选中列：" >
          {{pplForm.chosenColumns}}
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="pipelineVisible = false" size="medium">再想想</el-button>
            <el-button type="primary" @click="pipeline()" style="margin-left: 10px" size="medium">确定</el-button>
          </span>
      </template>
    </el-dialog>

  </div>

</div>
</template>

<script>
import {reactive, ref} from "vue";
import {deleteAnalysisConfig, getAnalysisConfig, getOneAnalysisConfig} from "../../api/analysisConfig";
import {ElMessage, ElMessageBox} from "element-plus";
import {visualize} from "../../api/analysis";
import {useRouter} from "vue-router";
import {addAnalysisPipeline} from "../../api/analysisPipeline";

export default {
  name: "Analysis",
  setup(){
    const query = reactive({
      file: "",
      name: "",
      pageIndex: 1,
      pageSize: 10,
    });
    const tableData = ref([]);
    const pageTotal = ref(0);
    let analysisVisible = ref(false);
    let selectConfigLen = ref();
    let selectConfigId = ref();
    let analysisType = ref();
    let selectConfigCol = ref([]);
    let methodMsg=ref("不同方法仅适用于特定特征字段");
    let methodMsg2=ref("不同方法仅适用于特定特征字段");
    const router = useRouter();

    const changeMethodMsg=()=>{
      let value = analysisType.value;
      if(value==='DATA_DISTRIBUTION'){
        methodMsg.value="请传入 1 个字段，类型不限（int/double/string）"
      }else if(value==='SCATTER_PLOT'){
        methodMsg.value="请传入 2-3 个 int/double 字段"
      }else if(value==='STATISTICS'){
        methodMsg.value="请传入 1 个 int/double 字段"
      }else if(value==='SKEWNESS_KURTOSIS'){
        methodMsg.value="请传入 1 个 int/double 字段"
      }else if(value==='PEARSON'){
        methodMsg.value="请传入2个 int/double 字段"
      }
    };
    const changeMethodMsg2=()=>{
      let value = pplForm.func;
      if(value==='DATA_DISTRIBUTION'){
        console.log(1)
        methodMsg2.value="请传入 1 个字段，类型不限（int/double/string）"
      }else if(value==='SCATTER_PLOT'){
        methodMsg2.value="请传入 2-3 个 int/double 字段"
      }else if(value==='STATISTICS'){
        methodMsg2.value="请传入 1 个 int/double 字段"
      }else if(value==='SKEWNESS_KURTOSIS'){
        methodMsg2.value="请传入 1 个 int/double 字段"
      }else if(value==='PEARSON'){
        methodMsg2.value="请传入2个 int/double 字段"
      }
    }

    let pipelineVisible = ref(false)
    const pplForm = reactive({
      func: '',
      pipelineName: '',
      chosenColumns: [],
    })
    const handlePipeline = (configId) => {
      console.log(configId)
      pipelineVisible.value = true
      getOneAnalysisConfig({configId}).then(res =>{
        pplForm.chosenColumns = res.result.chosenColumns
      })
    }
    const pipeline = () => {
      console.log(pplForm)
      const payload = {
        userId: localStorage.getItem("ms_userId"),
        pipelineName: pplForm.pipelineName,
        analysisFunction: pplForm.func,
        chosenColumns: pplForm.chosenColumns
      }
      if (payload.pipelineName === ""){
        alert("请填写信息！")
        return
      }
      addAnalysisPipeline(payload).then(res => {
        if (res.msg === '成功'){
          pipelineVisible.value = false
          ElMessageBox({
            title: '模型训练结果',
            message: `加入流水线成功！`,
            showCancelButton: true,
            confirmButtonText: '查看流水线',
            cancelButtonText: '留在本页面',
            beforeClose: (action, instance, done) => {
              if (action === 'confirm') {
                router.push("/analysisPipeline");
                done()
              } else {
                done()
              }
            },
          })
        }
        else{
          ElMessage.error("流水线生成失败!:"+res.msg);
        }
      })
    }

    const getPage=()=> {
      getAnalysisConfig({
        userId: localStorage.getItem("ms_userId")
      }).then(res => {
        console.log(res.result)
        tableData.value = res.result;
        console.log(tableData.value)
        pageTotal.value = tableData.value.length
      })
    };
    getPage();

    const handleDelete = (configId) => {
      ElMessageBox.confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
          .then(() => {
            deleteAnalysisConfig({configId}
            ).then(res=>{
              if(res.msg === '成功'){
                ElMessage.success("删除成功!")
                getPage();
              }
              else {
                ElMessage.error("删除失败:"+res.msg)
              }
            });
          })
          .catch(() => {});
    };

    const handleAnalysisResult = (configId) => {
      router.push({
        path:'analysisHistory',
        query:{
          configId: configId,
        }
      })
    };

    const startAnalysis = (index) => {
      selectConfigId = tableData.value[index].id;
      selectConfigLen.value = tableData.value[index].chosenColumns.length;
      selectConfigCol.value = tableData.value[index].chosenColumns;
      analysisVisible.value = true;
    };

    const analysis = () => {
      const payload={
        userId: localStorage.getItem("ms_userId"),
        configId: selectConfigId,
        func: analysisType.value,
      }
      console.log(payload)
      if (payload.func !== undefined){
        analysisVisible.value = false;
        ElMessage.info("开始数据分析");
        visualize(payload).then(res => {
          instance.confirmButtonLoading = false
          if (res.msg === '成功'){
            ElMessage.success("数据分析成功！");
            getPage();
          }
          else{
            ElMessage.error("数据分析失败！:"+res.msg);
          }
        }).catch(err=>{
          console.log(err)
        });
      }
      else {
        alert("请选择数据分析方法！");
        return;
      }
    }

    return{
      query,
      tableData,
      pageTotal,
      analysisVisible,
      selectConfigLen,
      analysisType,
      selectConfigCol,
      methodMsg,
      methodMsg2,
      selectConfigId,
      router,
      pplForm,
      pipelineVisible,
      getPage,
      handleDelete,
      handleAnalysisResult,
      startAnalysis,
      analysis,
      changeMethodMsg,
      changeMethodMsg2,
      handlePipeline,
      pipeline,
    };
  }
}
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.green {
  color: rgb(32, 220, 88)
}
.yellow{
  color:yellowgreen;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
